package com.swipemaster.activities;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.swipemaster.R;
import com.swipemaster.common.Const;
import com.swipemaster.common.Coords;
import com.swipemaster.common.Global;
import com.swipemaster.levels.levelinfo.LevelInfo;
import com.swipemaster.record.RecordsManager;

/** Adapter for a level selector visible as single square. */
public class LevelSelectorAdapter extends BaseAdapter
{
	private final Context context;

	public LevelSelectorAdapter(Context context)
	{
		this.context = context;
	}

	@Override
	public int getCount()
	{
		return Const.LEVELS;
	}

	@Override
	public Object getItem(int position)
	{
		return null;
	}

	@Override
	public long getItemId(int position)
	{
		return 0;
	}

	/** Create a new ViewGroup with TextView and Image for each item referenced by the Adapter. */
	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		View levelSelector;
		if (convertView == null)
		{
			// If it's not recycled, initialize some attributes.
			final LayoutInflater inflater = LayoutInflater.from(context);
			levelSelector = inflater.inflate(R.layout.level_selector, null);

			final int WIDTH = Coords.x(0.25);
			levelSelector.setLayoutParams(new GridView.LayoutParams(WIDTH, WIDTH));
		}
		else
		{
			levelSelector = convertView;
		}

		final TextView levelNumber = (TextView) levelSelector.findViewById(R.id.level_number);
		levelNumber.setVisibility(View.INVISIBLE);

		setStarsImage(levelSelector, position);
		final LevelInfo levelInfo = RecordsManager.getInfo(position);
		if (levelInfo.isLocked)
		{
			levelSelector.setBackgroundResource(R.drawable.lock_square_red2);
		}
		else
		{
			// Level is unlocked and free.
			setLevelNumber(levelNumber, position);
			if (levelInfo.isCompleted)
			{
				levelSelector.setBackgroundResource(R.drawable.green_square_simple);
			}
			else
			{
				levelSelector.setBackgroundResource(R.drawable.white_square_simple);
			}
		}

		return levelSelector;
	}

	private void setLevelNumber(TextView levelNumber, int position)
	{
		levelNumber.setVisibility(View.VISIBLE);
		levelNumber.setTypeface(Global.app.consts.font);
		levelNumber.setText(position + 1 + "");
	}

	private void setStarsImage(View levelSelector, int position)
	{
		final ImageView image = (ImageView) levelSelector.findViewById(R.id.image);
		final LevelInfo info = RecordsManager.getInfo(position);
		int stars = info.stars;
		if (info.isLocked || !info.isFree)
		{
			stars = -1;
		}
		image.setImageResource(Const.getStarsResource(stars));
	}
}